//
//  kindViewController.m
//  MoneyLog
//
//  Created by Max on 11-5-8.
//  Copyright 2011年 wicresoft. All rights reserved.
//

#import "KindListSelectedViewController.h"
#import "KindWrapper.h"
#import "GlobalDef.h"

extern NSString *kSectionTitleKey;
extern NSString *kRowItemKey;

@implementation KindListSelectedViewController
@synthesize _tableView;
@synthesize	titleString;
@synthesize dataSourceArray;
@synthesize kind;
@synthesize myViewDelegate;
@synthesize actionSheet;
@synthesize pickerDataSource;
@synthesize _pickerView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [_tableView release];
    [titleString release];
	[dataSourceArray release];
    [kind release];
    [myViewDelegate release];
    [actionSheet release];
    [pickerDataSource release];
    [_pickerView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = titleString; 
	self._tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
	self._tableView.rowHeight = 40;
    
    //ActionSheet
    actionSheet = [[UIActionSheet alloc] 
                   initWithTitle:@""
                   delegate:self 
                   cancelButtonTitle:nil 
                   destructiveButtonTitle:nil
                   otherButtonTitles:nil]; 
	actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    
    //PickerView
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
    _pickerView.showsSelectionIndicator = YES;						 
    _pickerView.delegate = self;
    _pickerView.dataSource = self; 
    _pickerView.tag=0xF001;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return [dataSourceArray count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSDictionary *dictionary = [dataSourceArray objectAtIndex:section];
    NSMutableArray *array = [dictionary objectForKey:kRowItemKey];
    
    return [array count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *title=@"";
    
    if ([self.dataSourceArray count]!= 1) {
        title = [[self.dataSourceArray objectAtIndex:section] objectForKey:kSectionTitleKey];
    }
    
    return title;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"GroupCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell... 
    
    NSDictionary *dictionary = [dataSourceArray objectAtIndex:indexPath.section];
    NSMutableArray *array = [dictionary objectForKey:kRowItemKey];
    
    KindWrapper *tempKind = [array objectAtIndex:indexPath.row]; 
    NSString *text = tempKind.kindName;
    cell.textLabel.text= text;
    
    UIButton *button =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    button.tag = (indexPath.section +1 ) *1000 + indexPath.row;
    [button addTarget:self action:@selector(markAction:) forControlEvents:UIControlEventTouchUpInside];
    if (tempKind.mark) {
        [button setImage:[UIImage imageNamed:@"Icon-rate-2.png"] forState:UIControlStateNormal];
    }
    else
    {
        [button setImage:[UIImage imageNamed:@"Icon-rate-1.png"] forState:UIControlStateNormal];
    }
    
    cell.accessoryView = button;
    if ([self.kind.kindName isEqualToString:text]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        cell.textLabel.textColor = [UIColor blueColor];
    }
    else
    {
        cell.textLabel.textColor = [UIColor blackColor];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return cell;
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    KindWrapper *tempKind = [[[self.dataSourceArray objectAtIndex:indexPath.section] objectForKey:kRowItemKey] objectAtIndex:indexPath.row];
    self.kind = tempKind;
    if ([kind.type isEqualToString:@"收入"] || kind.parentId !=0)
    {
        [myViewDelegate myView:self.view id:kind];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        NSMutableArray *array = [g_Database getKind:[NSString stringWithFormat:@" type='支出' AND parentId=%d",kind.id]];
        [self.pickerDataSource removeAllObjects];
        self.pickerDataSource = array;
        [array release];
        
        [self._pickerView reloadAllComponents];

        //工具栏
        CGRect appRect = [[UIScreen mainScreen] applicationFrame];
        UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, appRect.size.width, 44)];
        toolBar.barStyle = UIBarStyleBlack;
        toolBar.translucent =YES;
        [toolBar sizeToFit];

        NSMutableArray *barItems = [[NSMutableArray alloc] init]; 
        
        UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] 
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemCancel 
                                       target:self 
                                       action:@selector(pickerCancel)];
        [barItems addObject:cancelButton];
        [cancelButton release];
        
        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] 
                                      initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
                                      target:self action:nil];
        [barItems addObject:flexSpace];
        
        //标题
        UIBarButtonItem *titleButton = [[UIBarButtonItem alloc] init];
        titleButton.style = UIBarButtonItemStylePlain;
        titleButton.title = @"选择子类";
        [barItems addObject:titleButton];
        [titleButton release];
        
        [barItems addObject:flexSpace];
        [flexSpace release];
               
        //确定按钮
        UIBarButtonItem *buttonDone = [[UIBarButtonItem alloc] 
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                                       target:self 
                                       action:@selector(pickerDone)];
        [barItems addObject:buttonDone]; 
        [buttonDone release];
        
        [toolBar setItems:barItems animated:YES];
        [barItems release];
    
        [actionSheet addSubview:toolBar];
        [actionSheet addSubview:_pickerView];    
        [actionSheet showInView:[UIApplication sharedApplication].keyWindow];
        [actionSheet setBounds:CGRectMake(0, 0, appRect.size.width, appRect.size.height)];
        
        [toolBar release];
    }   
}


#pragma mark - * UIPickerViewDelegate

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	if (pickerView.tag == 0xF001)
	{
        KindWrapper *tempKind = [self.pickerDataSource objectAtIndex: row];
        kind.subKindName = tempKind.kindName;
	}
      
}

#pragma mark - * UIPickerViewDataSource

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	NSString *content=@"";
	
	// note: custom picker doesn't care about titles, it uses custom views
	if (pickerView.tag == 0xF001)
	{
		if (component == 0)
		{
            KindWrapper *tempKind = [self.pickerDataSource objectAtIndex: row];
			content = tempKind.kindName; 
            
            NSLog(@"content = %@",content);
            NSLog(@"self.kind.subKindName =%@",self.kind.subKindName);
            if ([content isEqualToString:self.kind.subKindName]) {
                [pickerView selectRow:row inComponent:component animated:YES];
            }
		}
	}
	
	return content;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	CGFloat componentWidth = 0.0;
	
	if (component == 0)
		componentWidth = 280.0;	// first column size is wider to hold names
	//else
	//	componentWidth = 40.0;	// second column is narrower to show numbers
	
	return componentWidth;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
	return 40.0;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return [pickerDataSource count]; 
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}

#pragma mark - * Action sheet delegate method.

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // the user clicked one of the OK/Cancel buttons
    if (buttonIndex == 0)
    {
        exit(0);
    }
}

#pragma mark - * action

-(void)pickerDone{
    KindWrapper *tempKind = [self.pickerDataSource objectAtIndex: [_pickerView selectedRowInComponent:0]];
    kind.subKindName = tempKind.kindName;
    
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
    [myViewDelegate myView:self.view id:kind];
}

-(void)pickerCancel {
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

-(void) reloadData:(NSMutableArray *) array
{
    self.dataSourceArray = array;
    [self._tableView reloadData];
}

-(IBAction)markAction:(id)sender {
    NSLog(@"sender.tog=%d",[sender tag]);
    
    int tag = [sender tag];
    
    int section =tag /1000-1;
    int row = tag %1000;
     
    KindWrapper *tempKind = [[[self.dataSourceArray objectAtIndex:section] objectForKey:kRowItemKey] objectAtIndex:row];
    tempKind.mark = !tempKind.mark;
    
    if ( ![g_Database updateKind:tempKind] ) {
        UIAlertView * alertView = [[UIAlertView alloc] 
                                   initWithTitle:@"提示" 
                                   message:@"更新类别失败了！"
                                   delegate:nil 
                                   cancelButtonTitle:@"确定" 
                                   otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
    else
    {
        if ([self.dataSourceArray count] !=1) {
            
            [self.dataSourceArray removeAllObjects];
                       
            NSMutableArray *array = [g_Database getMarkKind];
            NSDictionary *markDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                            @"收藏",kSectionTitleKey,
                                            array,kRowItemKey,nil];
            [self.dataSourceArray addObject:markDictionary];
            [array release];
            
            array = [g_Database getCommonKind:7];
            NSDictionary *commonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                              @"常用",kSectionTitleKey,
                                              array,kRowItemKey,nil];
            [self.dataSourceArray addObject:commonDictionary];
            [array release];
            
            [self._tableView reloadData];
        }
        else
        {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
            UITableViewCell *cell = [self._tableView cellForRowAtIndexPath:indexPath];
            
            UIButton *button =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
            button.tag = (indexPath.section +1 ) *1000 + indexPath.row;
            [button addTarget:self action:@selector(markAction:) forControlEvents:UIControlEventTouchUpInside];
            
            if (tempKind.mark) {
                [button setImage:[UIImage imageNamed:@"Icon-rate-2.png"] forState:UIControlStateNormal];
            }
            else
            {
                [button setImage:[UIImage imageNamed:@"Icon-rate-1.png"] forState:UIControlStateNormal];
            }
            
            
            cell.accessoryView = button;
        }
    }
}

@end
